package com.example.demo.controller;

import com.example.demo.util.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class FileController {

    @Value("${web.upload-path}")
    private String uploadPath;
    private String fileName = "watermark.png";

    /**
     * 跳转到文件上传页面
     *
     * @return
     */
    @GetMapping("upload")
    public String toUpload() {
        return "file/upload";
    }

    /**
     * @param image 要上传的图片
     * @return
     */
    @PostMapping("upload")
    public void uploadImage(@RequestParam("file") MultipartFile image, HttpServletResponse response) throws IOException {
        FileUtil.uploadImage(image, uploadPath, fileName);
        response.sendRedirect("/download");
    }

    /**
     * @param response 响应对象
     * @return
     */
    @GetMapping("download")
    public void downloadImage(HttpServletResponse response) {
        //设置文件路径
        File file = new File(uploadPath + File.separator + fileName);
        if (file.exists()) {
            //第一步：设置响应类型, 强制下载不打开
            response.setContentType("application/force-download");
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                //第二读取文件
                fis = new FileInputStream(file);
                response.setContentLength(fis.available());
                bis = new BufferedInputStream(fis);
                //第三步：读文件写入http响应
                OutputStream os = response.getOutputStream();
                int len = 0;
                while ((len = bis.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
